<?php
require_once("dao/FacturePonctuelleDao.php");
require_once("dao/CommandeDao.php");

use iio\libmergepdf\Merger;
use iio\libmergepdf\Pages;
//@ todo passer tout ça dans des templates propres

/**
 * Fonction de génération du pdf de facture ponctuelle
 * @param stdClass $facture
 */
function genererPdfFacturePonctuelle(stdClass $facture) {
    // récupération du pied de page 
    $myFile = "facture.txt";
    $fh = fopen($myFile, 'r');
    $footer = fread($fh, filesize($myFile));
    fclose($fh);
    ob_start();
    ?>
    <page style="font-size: 12px" backtop="30mm" backbottom="30mm" backleft="15mm" >

        <page_header>
            <div style="position: absolute; left: 50px"> 
                <img src="./logo-facture/hto.png" >
            </div>
        </page_header>

        <div style="position: absolute; left: 400px; top: 10px; font-size: 14px">
            <?php
            if ($facture->client->raison_social == null) {
                $nom = $facture->client->prenom . " " . $facture->client->nom;
            } else {
                $nom = $facture->client->raison_social;
            }
            echo "<br>" . $nom;
            echo "<br>" . $facture->client->adresse;
            echo "<br>" . $facture->client->cp . " " . $facture->client->ville;
            ?>
        </div>
        <div style="position: absolute; left: 0px; top:150px; font-size: 12px">    
            <?php
            if ($facture->is_avoir) {
                //reference client
                echo 'Référence client: ' . $facture->client->code_client_hto;
                echo '<br>Num avoir: p-' . date("Y") . date("m") . $facture->client->code_client_hto;
                echo '<br>Date de l\'avoir: ' . date("d/m/Y");
            } else {
                //reference client
                echo 'Référence client: ' . $facture->client->code_client_hto;
                echo '<br>Num Facture: p-' . date("Y") . date("m") . $facture->client->code_client_hto;
                echo '<br>Date facturation: ' . date("d/m/Y");
            }
            ?>
        </div>
        <div style="position: absolute; left: 0px; top:250px; font-size: 12px">
            <style type="text/css"> 
                <!--
                table {
                    border-collapse: collapse
                }
                td, th
                {
                    padding-right:15px;
                    border-bottom:1px solid #CDD3E0;
                    border-top:1px solid #FFFFFF;
                }
                -->
            </style>
            <br><br><br><br>
            <table width="560" align="left">
                <thead>
                    <tr>
                        <th width="350" align="left">Offre</th>
                        <th>Quantité</th>
                        <th>Prix unitaire HT</th>
                        <th>Prix total HT</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $totalHT = 0;
                    foreach ($facture->lignes as $offre):
                        ?> 
                        <tr>
                            <td align="left"><?php echo $offre->libelle; ?></td> 
                            <td align="right"><?php echo $offre->quantite; ?></td> 
                            <td align="right"><?php echo number_format(round($offre->prix_0, 2), 2); ?>&nbsp;€</td> 
                            <td align="right"><?php echo number_format(round($offre->prix, 2), 2); ?>&nbsp;€</td>
                        </tr>
                        <?php
                        $totalHT += (float) $offre->prix;
                    endforeach;
                    ?>
                </tbody>
                <tfoot>
                    <tr><td colspan="4"><br></td></tr>
                    <tr>
                        <th colspan="3">Total HT</th>
                        <td align="right"><?php echo number_format(round($totalHT, 2), 2); ?>&nbsp;€</td> 
                    </tr>
                    <tr>
                        <th colspan="3">TVA 20%</th>
                        <td align="right"><?php echo number_format(round($totalHT * 0.2, 2), 2); ?>&nbsp;€</td> 
                    </tr>
                    <tr>
                        <th colspan="3">Total TTC</th>
                        <th align="right"><?php echo number_format(round($totalHT * 1.2, 2), 2); ?>&nbsp;€</th> 
                    </tr>
                </tfoot>
            </table>
            <br><br><br><br>
            <?php
            if(!$facture->is_avoir){
                switch ($facture->mode_paiement) {
                    case 'prv':
                        $compte = $facture->client->code_etablissement 
                            . ' ' . $facture->client->code_guichet 
                            . ' ' . $facture->client->num_compte
                            . ' ' . $facture->client->rib;
                        echo "Le montant de votre facture sera prélevé sur le compte $compte";
                        break;
                    case 'vrm':
                        echo "Paiement par Virement : " . RIB;
                        break;
                    case 'chq':
                        echo "Paiement par Chèque";
                        break;
                    case 'mdt':
                        echo "Paiement par Mandat administratif : " . RIB;
                        break;

                    default:
                        break;
                }
            }
            ?>
        </div>
        <page_footer>
            <?php
            echo $footer;
            ?>	
        </page_footer> 
    </page>
    <?php
//$dir="facture/".date("mY");
    $dir = "facture_temp/" . date("mY");
    $dir2 = "facture/" . date("mY");
    if (!is_dir($dir)) {
        mkdir($dir);
    }
    if (!is_dir($dir2)) {
        mkdir($dir2);
    }
    $content = ob_get_clean();
    require_once(dirname(__FILE__) . '/../../../lib/html2pdf/html2pdf.class.php');
    $pdf = new HTML2PDF('P', 'A4', 'fr', true, 'utf-8');
    $pdf->WriteHTML($content, isset($_GET['vuehtml']));
    if (is_dir($dir)) {
        
    } else {
        mkdir($dir);
    }
    $file = $dir . "/Ponctuelle-" . $facture->client->code_client_hto . "-" . $facture->id . "-" . date("mY") . ".pdf";
    $pdf->Output($file, 'F');

// maj pdf facture
    $q = "UPDATE factures_ponctuelles SET pdf = '$file' WHERE id = $facture->id;";
    FacturePonctuelleDao::exec($q);
    $facture->pdf = $file;
    return $facture;
}

function genererPdfCommande(stdClass $commande) {
    // récupération du pied de page 
    $myFile = "facture.txt";
    $fh = fopen($myFile, 'r');
    $footer = fread($fh, filesize($myFile));
    fclose($fh);
    ob_start();
    ?>
    <style type="text/css">
	.content-bill {
		font-size: 10pt;
		margin-top:20px;
		margin-bottom:20px;
		height:auto;
		width:100%;
		/*background-color:#e8b3fb;*/
	}   
	
	.table {
		border-collapse:collapse;
		border:0;
	}
	
	.signature {
		height:auto;
		/*background-color:#d9d9d9;*/
		margin-top:20px;
		border-top:2px solid #d9d9d9;
		padding-top:20px;
                width: auto;
                
	}
		
	.reference-bill {
                border-top:2px solid #d9d9d9;
		margin-bottom:20px;
	}
	
	.signature table, .signature table thead, .signature table tr, .signature table tr td {
		vertical-align:top;
	}
	
	.signature table {
		margin-top:40px;
	}
	
	.signature-left {
		width:312px;
	}
	
	.signature-right {
		/*background-color:#fbd0b3;*/
		width:312px;
		border:1px solid black;
		padding:4px;
	}
	
	.grey td, .grey th {
		background-color:#ededed;
	}
    </style>
    <page style="font-size: 12px" backtop="20mm" backbottom="20mm" backleft="15mm"  backright="15mm">
	<page_header>
		<div style="margin-left: 50px;"> 
			<img src="./logo-facture/hto.png" >
		</div>
	</page_header>
        <div class="content-bill">
            <h3>Commande du <?php echo date("d/m/Y"); ?></h3>
            <div class="reference-bill">
                <h4>Coordonnées clients</h4>
                <?php 
                    if ($commande->client->raison_social == null) {
                        $nom = $commande->client->prenom . " " . $commande->client->nom;
                    } else {
                        $nom = $commande->client->raison_social;
                    }
                ?>
                <table width="750" align="left" cellspacing="0" cellpadding="0">
                    <tbody>
                        <tr>
                            <th style='width: 15%'>Raison sociale :</th>
                            <td style='width: 25%'><?php echo $nom; ?></td>
                            <th style='width: 10%'>N° siret :</th>
                            <td style='width: 23%'><?php echo $commande->client->siret; ?></td>
                            <th style='width: 5%'>APE :</th>
                            <td style='width: 22%'><?php echo $commande->client->ape; ?></td>
                        </tr>
                        <tr>
                           <th>Adresse :</th>
                            <td colspan="5"><?php echo $commande->client->adresse; ?></td>
                        </tr>
                        <tr>
                            <th>&nbsp;</th>
                            <td colspan="3"><?php echo $commande->client->cp.'  '.$commande->client->ville; ?></td>
                        </tr>
                        <tr><td colspan="6">&nbsp;</td></tr>
                        <tr>
                            <th>Référence client :</th>
                            <td> <?php echo $commande->client->code_client_hto; ?></td>
                            <th>Num Commande :</th>
                            <td> <?php echo 'c-' . date("Y") . date("m") . $commande->client->code_client_hto; ?></td>
                            <th>Date :</th>
                            <td> <?php echo date("d/m/Y"); ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <?php 
            $totalHT = 0;
            $portabilite = false; 
            $i=0;
            ?>
            <h4>Abonnement, service et options</h4>
           <table width="830" align="left" cellspacing="0" cellpadding="0">
               <tbody>
                    <?php foreach ($commande->lignes as $ligne): ?>
                    <?php 
                    $portabilite = (!empty($ligne->msisdn) && !empty($ligne->numero_rio) && !empty($ligne->date_souhaite));
                    $i++;
                    ?>
                        <tr>
                            <th style='width: 2%'>#</th>
                            <th style='width: 20%'>Utilisateur</th>
                            <th style='width: 18%'>Numéro SIM</th>
                            <th style='width: 20%'>Désignation de l'offre</th>
                            <th style='width: 10%'>Engagement</th>
                            <th style='width: 20%' align="right">Prix € HT</th>
                        </tr>
                        <tr>
                            <td><?php echo $i; ?></td>
                            <td><?php echo $ligne->utilisateur; ?></td>
                            <td><?php echo $ligne->carte_sim; ?></td>
                            <td><?php echo substr($ligne->offre_nom, 0, 30); if(strlen($ligne->offre_nom)>30){ echo '<br>'; echo substr($ligne->offre_nom, 31, strlen($ligne->offre_nom));} ?></td>
                            <td><?php echo $ligne->engagement == 0 ? 'Sans engagement': $ligne->engagement.' mois' ; ?></td>
                            <td align="right"><?php echo $ligne->prix; ?>&nbsp;€</td>
                        </tr>
                        <?php if (!empty($ligne->equipement)): ?>
                            <tr>
                                <td>&nbsp;</td>
                                <th colspan="5">Equipement :</th>
                            </tr>
                             <tr>
                                <td>&nbsp;</td>
                                <td colspan="4"><?php echo $ligne->equipement->libelle; ?></td>
                                <td align="right"><?php echo $ligne->equipement->terminal_prix; ?>&nbsp;€</td>
                            </tr>
                             <?php $totalHT += (float) $ligne->equipement->terminal_prix; ?>
                        <?php endif; ?>
                        <?php if (!empty($ligne->optionsMobiles)): ?>
                            <tr>
                                <td>&nbsp;</td>
                                <th colspan="5">Options mobiles :</th>
                            </tr>
                            <?php foreach ($ligne->optionsMobiles as $option): ?>
                                <tr>
                                    <td>&nbsp;</td>
                                    <td colspan="4"><?php echo $option->nom; ?></td>
                                    <td align="right"><?php echo $option->prix_seul; ?>&nbsp;€</td>
                                </tr>
                                <?php $totalHT += (float) $option->prix_seul; ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    <?php if($portabilite): ?>
                        <tr>
                            <td>&nbsp;</td>
                            <th colspan="5">Portabilité :</th>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <th>Numéro de ligne</th>
                            <th>Numéro RIO</th>
                            <th colspan="3">Port à date souhaitée</th>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td><?php echo $ligne->msisdn; ?>&nbsp;</td>
                            <td><?php echo $ligne->numero_rio; ?>&nbsp;</td>
                            <td><?php echo $ligne->date_souhaite; ?></td>
                            <td colspan="2" align="right">0.00&nbsp;€</td>
                        </tr>
                    <?php endif; ?>
                    <?php $totalHT += (float) $ligne->prix; ?>
                    <tr><td class="gap" colspan="6">&nbsp;</td></tr>
                    <?php endforeach; ?>
               </tbody>
               <tbody>
                <tr>
                    <th align="right" colspan="5">Total HT</th>
                    <td align="right"><?php echo $totalHT; ?>&nbsp;€</td> 
                </tr>
                <tr>
                    <th align="right" colspan="5">TVA 20%</th>
                    <td align="right"><?php echo round($totalHT * 0.2, 2); ?>&nbsp;€</td> 
                </tr>
                <tr>
                    <th align="right" colspan="5">Total TTC</th>
                    <th align="right"><?php echo round($totalHT * 1.2, 2); ?>&nbsp;€</th> 
                </tr>
               </tbody>
            </table>
            <div class="signature">
                 <span class="legals">
                        Je certifie l'exatitude des informations figurant sur le present Contrat de service et reconnais avoir reçu un exemplaire des Conditions Générale de Service relatives à l'offre souscrite, en avoir pris connaissance et les accepter dans toute leur teneur.
                 </span>
                 <table>
                     <tbody>
                         <tr>
                             <td class="signature-left">
                             Nom du signataire : 
                             <br/>
                             Qualité :
                             <br/>
                             Fait à :
                             <br/>
                             Le : 
                             </td>
                             <td class="signature-right">
                                 <span class="description">Signature et cachet du client :</span>
                             </td>
                         </tr>
                     </tbody>
                 </table>
             </div>
        </div>
        <page_footer>
            <?php
            echo $footer;
            ?>	
        </page_footer> 
    </page>
    <?php
    $dir = "commandes/" . date("mY");
    if (!is_dir($dir)) {
        mkdir($dir);
    }
    $content = ob_get_clean();
//    echo $content;
//    die();
    require_once(dirname(__FILE__) . '/../../../lib/html2pdf/html2pdf.class.php');
    $pdf = new HTML2PDF('P', 'A4', 'fr', true, 'utf-8');
    $pdf->WriteHTML($content, isset($_GET['vuehtml']));

    $file = $dir . "/Commande-" . $commande->client->code_client_hto . "-" . $commande->commande->id . "-" . date("mY") . ".pdf";
    $pdf->Output($file, 'F');

    $m = new Merger();
    $m->addFromFile($file);
    $m->addFromFile(__DIR__.'/../../pdf-assets/commande/mandat_sepa.pdf', new Pages('1-1'));
    $m->addFromFile(__DIR__.'/../../pdf-assets/commande/CGA.pdf', new Pages('1-2'));
    file_put_contents($file, $m->merge());
    // maj pdf commande
    $q = "UPDATE commande SET pdf = '$file' WHERE id = " . $commande->commande->id . ";";
    CommandeDao::exec($q);
    $facture->pdf = $file;
    return $facture;
}
